package com.xiaoyan.texteditor.service;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * ClassName: SaveFileServiceImpl
 * Package: com.xiaoyan.texteditor.service
 * Description:
 *
 * @Author Xiaoyan_Lu
 * @Create 2023/12/2 22:28
 * @Version 1.0
 */
public class SaveFileServiceImpl implements SaveFileService{
    private static BufferedWriter bufferedWriter = null;
    @Override
    public void save(String path, JTextArea jTextArea) {
        String name = addSuffixName(path);
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(name));
            bufferedWriter.write(jTextArea.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /* *
     * @Description: 给文件添加后缀
     * @param [java.io.File]
     * @return java.lang.String
     * @version v1.0
     * @author xiaoyan_lu
     * @date 2023/12/2 22:58
     */
    private String addSuffixName(String path) {
        //1.得到文件名
        StringBuilder name = new StringBuilder(path.trim());
        //2.获取文件名后缀
        int lastIndex = name.lastIndexOf(".");
        String suffixName = name.substring(lastIndex+1);
        //3.判断后缀,如果不为txt,则添加txt
        if(!suffixName.equals("txt")){
            name.append(".txt");
        }
        return String.valueOf(name);
    }
}
